﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Development.Tools
{
    public class InputAdapter 
    {
        protected Task m_Thread = null;
        protected bool m_isRun = false;

        protected string m_inputString = "";
        public delegate void InputProc(List<string> param);

        protected Dictionary<string, InputProc> m_proc = new Dictionary<string, InputProc>();

        public InputAdapter()
        {
            RegisterProc();
        }

        protected virtual void RegisterProc()
        {

        }

        public void StartInput()
        {
            m_Thread = new Task(InputRoutine);
            m_Thread.Start();
            m_isRun = true;
        }

        public void StopInput()
        {
            m_isRun = false;
            if (m_Thread != null)
            {
                m_Thread = null;
            }
        }

        public void OnError()
        {
            Log.WriteLog(ELogLevel.LOG_ERROR, "参数错误");
        }

        void InputRoutine()
        {
            while (m_isRun)
            {
                m_inputString = Console.ReadLine();
                string[] cmd = m_inputString.Split(' ');
                if (cmd.Length > 0)
                {
                    string key = cmd[0];
                    if (m_proc.ContainsKey(key))
                    {
                        List<string> param = new List<string>();
                        if (cmd.Length > 1)
                        {
                            for (int i = 1; i < cmd.Length; ++i)
                            {
                                param.Add(cmd[i]);
                            }
                        }
                        m_proc[key](param);
                    }
                    else
                    {
                        Log.WriteLog(ELogLevel.LOG_ERROR, "未知命令");
                    }
                }


            }
        }


        
    }



        
}
